package com.Confinement;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * Created by mike on 17/10/25.
 */
public class WorkThread<T,V> implements Runnable{
    private TaskProcesser<T,V> processer;
    private BlockingQueue<Runnable> queue;
    public WorkThread(TaskProcesser<T,V> processer,BlockingQueue<Runnable> queue){
        this.processer = processer;
        this.queue = queue;
    }
    public Future<V> submit(final T task) throws InterruptedException {
        Callable<V> callable = new Callable<V>() {
            @Override
            public V call() throws Exception {
                return processer.doProcess(task);
            }
        };
        FutureTask<V> futureTask = new FutureTask<V>(callable);
        queue.put(futureTask);
        return futureTask;
    }

    @Override
    public void run() {
        Runnable r = null;
        try {
            r = queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(r).start();
    }
}
